'use strict';

const _ = require('lodash');
const Controller = require('@cvte/fm-egg-plus').Controller;

class ApisController extends Controller {
  async index() {
    const actionName = this.ctx.query['actionName'];
    const params = this.ctx.request.body || {};

    // 请求不存在的 actionName，返回404
    if (!actionName || !(_.has(this.app.apis, actionName))) {
      const respData = {
        success: false,
        error_code: 404,
        message: 'Action ' + actionName + ' is not exist!',
      };
      this.ctx.status = 404;
      this.ctx.body = respData;
    } else {
      try {
        // 请求后台接口，并返回结果
        const result = await this.ctx.callAPI(actionName, { params: params });
        this.ctx.body = result.res.data;
      } catch (error) {
        this.ctx.status = 500;
        this.ctx.body = {
          success: false,
          message: error.message,
          error_code: _.get(error, 'response.status') || 500,
        }
      }
    }
  }
}

module.exports = ApisController;